package com.example.roamio.interceptor;

import com.example.roamio.util.RedisKeyUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate redisTemplate;

    public static final ThreadLocal<Integer> CURRENT_USER_ID = new ThreadLocal<>();

    public LoginInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");
        if (token == null) {
            log.warn("请求缺少 token，拒绝访问");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        String userIdStr = redisTemplate.opsForValue().get(RedisKeyUtil.tokenKey(token));
        if (userIdStr == null) {
            log.warn("token 无效或已过期");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        try {
            Integer userId = Integer.parseInt(userIdStr);
            CURRENT_USER_ID.set(userId);
            log.info("当前登录用户ID：{}", userId);
        } catch (NumberFormatException e) {
            log.error("Redis 中的 userId 不是有效整数: {}", userIdStr);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        CURRENT_USER_ID.remove();
    }
}